package m202405.d17;

import java.util.Arrays;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/17 15:58
 */
public class Q31 {

    public static void main(String[] args) {
        Q31 q31 = new Q31();
        q31.nextPermutation(new int[]{1,3,2});
    }


    private void nextP(int[] nums){
        int i = nums.length - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }
        if (i >= 0) {
            int j = nums.length - 1;
            while (j >= 0 && nums[i] >= nums[j]) {
                j--;
            }
            swap(nums, i, j);
        }
        System.out.println();
    }

    public void nextPermutation(int[] nums) {
        if (nums.length <= 1) {
            return;
        }
        if (nums[nums.length - 1] > nums[nums.length - 2]) {
            swap(nums, nums.length - 1, nums.length - 2);
            return;
        }

        int i = nums.length - 1;
        for (; i >= 0; i--) {
            if (i == 0) {
                Arrays.sort(nums);
                return;
            }
            if (nums[i] > nums[i - 1]) {
                break;
            }
        }
        for (int length = nums.length; length > i; length--) {
            if (nums[length - 1] > nums[i - 1]) {
                swap(nums, i - 1, length - 1);
                break;
            }
        }
        Arrays.sort(nums, i, nums.length);
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
